package com.hilaver.dzmis.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;

import com.hilaver.dzmis.product.ProductIdentification;
import com.hilaver.dzmis.product.ProductOrderItemColor;
import com.hilaver.dzmis.product.ProductYarn;

public class ProcurementDAO extends BaseHibernateDAO {

	public Integer[] getProductIdentificationIdFromYarn(Integer pId,
			Integer pyId) throws Exception {
		String hql = "select pi.id from "
				+ ProductIdentification.class.getName()
				+ " pi, "
				+ ProductYarn.class.getName()
				+ " py where pi.isHistory = 0 and pi.procurement.id = ? and pi.id = py.productIdentification.id and py.biYarn.id = ?";
		try {
			Query queryObject = getSession().createQuery(hql);
			queryObject.setParameter(0, pId);
			queryObject.setParameter(1, pyId);
			List<Integer> result = queryObject.list();
			Integer[] rtn = new Integer[result.size()];
			for (int i = 0; i < result.size(); i++) {
				rtn[i] = result.get(i);
			}
			return rtn;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public List<ProductIdentification> getProductIdentificationsFromIds(
			Integer[] ids) throws Exception {
		if (ids == null || ids.length == 0) {
			return new ArrayList<ProductIdentification>();
		}
		String hql = "from " + ProductIdentification.class.getName()
				+ " where id in " + getIds(ids);
		try {
			Query queryObject = getSession().createQuery(hql);
			List<ProductIdentification> result = queryObject.list();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public String[] getDiffProductOrderItemColorIds(
			List<ProductIdentification> piList) throws Exception {
		if (piList.size() == 0) {
			return new String[0];
		}
		String hql = "select distinct(pantoneNumber) from "
				+ ProductOrderItemColor.class.getName()
				+ " where productOrderItem.productIdentification.id in "
				+ getIds(piList) + " order by id";
		try {
			Query queryObject = getSession().createQuery(hql);
			List<String> result = queryObject.list();
			String[] rtn = new String[result.size()];
			for (int i = 0; i < result.size(); i++) {
				rtn[i] = result.get(i);
			}
			return rtn;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public ProductIdentification getProductIdentification(Integer piId,
			String pantonColor) {
		return null;
	}

	private String getIds(Integer[] ids) {
		String rtn = "";
		rtn += "(";
		for (int i = 0; i < ids.length; i++) {
			rtn += ids[i];
			if (i != (ids.length - 1)) {
				rtn += ", ";
			}
		}
		rtn += ")";
		return rtn;
	}

	private String getIds(List<ProductIdentification> piList) {
		String rtn = "";
		rtn += "(";
		for (int i = 0; i < piList.size(); i++) {
			rtn += ((ProductIdentification) piList.get(i)).getId();
			if (i != (piList.size() - 1)) {
				rtn += ", ";
			}
		}
		rtn += ")";
		return rtn;
	}
}
